package com.qyhl.module_practice.map;

import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.gyf.immersionbar.ImmersionBar;
import com.qyhl.module_practice.R;
import com.qyhl.module_practice.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.civilized.PracticeListBean;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = ARouterPathConstant.PRACTICE_MAP)
public class PracticeMapActivity extends BaseActivity implements PracticeMapContract.PracticeMapView, AMap.OnMapLoadedListener, AMap.OnMarkerClickListener, AMap.OnInfoWindowClickListener {
    @BindView(R2.id.map)
    MapView mMapView;
    @BindView(R2.id.flow_layout)
    TagFlowLayout flowLayout;
    @BindView(R2.id.recycle_view)
    RecyclerView recyclerView;

    private AMap aMap;

    private int lastCheckId = -1;

    private List<LatLng> latLngList = new ArrayList<>();

    private List<PracticeListBean> mDataList = new ArrayList<>();

    private List<PracticeListBean> indexList = new ArrayList<>();

    private List<PracticeListBean> siteList = new ArrayList<>();

    private List<PracticeListBean> instList = new ArrayList<>();

    private List<PracticeListBean> adapterList = new ArrayList<>();

    private CommonAdapter<PracticeListBean> commonAdapter;

    @Override
    protected int getContentView() {
        return R.layout.practice_activity_map;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        String instId = getIntent().getStringExtra("instId");
        PracticeMapPresenter mPresenter = new PracticeMapPresenter(this);

        List<IndexBean> subList = new ArrayList<>();

        if (CommonUtils.getInstance().getSite() != 140) {
            subList.add(new IndexBean("实践中心", R.drawable.practice_map_center_icon));
            subList.add(new IndexBean("实践所", R.drawable.practice_map_inst_icon));
            subList.add(new IndexBean("实践站", R.drawable.practice_map_site_icon));
            subList.add(new IndexBean("服务站", R.drawable.practice_map_service_icon));
        } else {
            subList.add(new IndexBean("实践中心", R.drawable.practice_map_center_qixia_icon));
            subList.add(new IndexBean("实践所", R.drawable.practice_map_inst_qixia_icon));
            subList.add(new IndexBean("实践站", R.drawable.practice_map_site_qixia_icon));
            recyclerView.setLayoutManager(new LinearLayoutManager(this));
            DividerItemDecoration divider = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
            divider.setDrawable(ContextCompat.getDrawable(this, R.drawable.practice_item_news_divider));
            recyclerView.addItemDecoration(divider);
            recyclerView.setAdapter(commonAdapter = new CommonAdapter<PracticeListBean>(this, R.layout.practice_map_item_qixia, adapterList) {
                @Override
                protected void convert(ViewHolder holder, PracticeListBean bean, int position) {
                    if (bean.isSelected()) {
                        holder.setImageResource(R.id.select_tag, R.color.global_base);
                    } else {
                        holder.setImageResource(R.id.select_tag, R.color.global_base_40per);
                    }

                    holder.setText(R.id.title, bean.getName());

                    holder.setText(R.id.address, bean.getAddress());
                }
            });
        }

        flowLayout.setAdapter(new TagAdapter<IndexBean>(subList) {
            @Override
            public View getView(FlowLayout parent, int position, IndexBean bean) {
                TextView tv = (TextView) LayoutInflater.from(PracticeMapActivity.this).inflate(R.layout.practice_item_practice_map,
                        flowLayout, false);
                tv.setText(bean.getName());
                tv.setCompoundDrawablesWithIntrinsicBounds(null, ContextCompat.getDrawable(PracticeMapActivity.this, bean.getRes()), null, null);
                return tv;
            }
        });

        flowLayout.setMaxSelectCount(1);


        if (aMap == null) {
            aMap = mMapView.getMap();
            aMap.setOnMapLoadedListener(PracticeMapActivity.this);// 设置amap加载成功事件监听器
            aMap.setOnMarkerClickListener(this);
        }
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.interval(2000);
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));
        myLocationStyle.showMyLocation(true);
        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        aMap.setMyLocationEnabled(true);

        InfoWinAdapter adapter = new InfoWinAdapter(this);
        aMap.setInfoWindowAdapter(adapter);
        aMap.setOnInfoWindowClickListener(this);

        mPresenter.getList(instId);

    }

    @Override
    protected void setListener() {
        //流布局点击
        flowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                lastCheckId = -1;
                if (flowLayout.getSelectedList().size() < 1) {
                    if (CommonUtils.getInstance().getSite() == 140) {
                        if (recyclerView.getVisibility() == View.VISIBLE) {
                            recyclerView.setVisibility(View.GONE);
                        }
                    }
                }
                for (Integer pos : flowLayout.getSelectedList()) {
                    switch (pos) {
                        case 0://实践中心
                            if (CommonUtils.getInstance().getSite() == 140) {
                                if (recyclerView.getVisibility() == View.VISIBLE) {
                                    recyclerView.setVisibility(View.GONE);
                                }
                            }
                            lastCheckId = 0;
                            initMark(lastCheckId);
                            break;
                        case 1://实践所
                            if (CommonUtils.getInstance().getSite() == 140) {
                                recyclerView.setVisibility(View.VISIBLE);
                            }
                            lastCheckId = 1;
                            initMark(lastCheckId);
                            break;
                        case 2://实践站
                            if (CommonUtils.getInstance().getSite() == 140) {
                                recyclerView.setVisibility(View.VISIBLE);
                            }
                            lastCheckId = 2;
                            initMark(lastCheckId);
                            break;
                        case 3://服务站
                            if (CommonUtils.getInstance().getSite() == 140) {
                                if (recyclerView.getVisibility() == View.VISIBLE) {
                                    recyclerView.setVisibility(View.GONE);
                                }
                            }
                            lastCheckId = 3;
                            initMark(lastCheckId);
                            break;
                        default:
                            break;
                    }
                }

                return false;
            }
        });

        if (CommonUtils.getInstance().getSite() == 140) {
            commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int position) {
                    List<PracticeListBean> selectList = new ArrayList<>();
                    for (int i = 0; i < adapterList.size(); i++) {
                        if (position == i) {
                            adapterList.get(i).setSelected(true);
                            selectList.add(adapterList.get(i));
                        } else {
                            adapterList.get(i).setSelected(false);
                        }
                    }
                    commonAdapter.notifyDataSetChanged();

                    if (StringUtils.isNotEmpty(selectList.get(0).getLatitude()) && StringUtils.isNotEmpty(selectList.get(0).getLongitude())) {
                        refreshMap(selectList,true);
                        recyclerView.setVisibility(View.GONE);
                    } else {
                        showToast("无详细地址！");
                    }

                }

                @Override
                public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int position) {
                    return false;
                }
            });
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
        ActionLogUtils.getInstance().onResume(this, ActionConstant.PRACTICE_MAP);
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
        ActionLogUtils.getInstance().onResume(this, ActionConstant.PRACTICE_MAP);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mMapView.onCreate(savedInstanceState);
    }

    @OnClick(R2.id.back_btn)
    public void onViewClicked() {
        finish();
    }

    @Override
    public void setList(List<PracticeListBean> beanList) {
        mDataList.addAll(beanList);
        initMark(lastCheckId);
    }

    private void initMark(int lastCheckId) {
        indexList.clear();
        switch (lastCheckId) {
            case 0:
                for (int i = 0; i < mDataList.size(); i++) {
                    if (mDataList.get(i).getType().equals("NORMAL")) {
                        if (mDataList.get(i).getLevel() == 0) {
                            indexList.add(mDataList.get(i));
                        }
                    }
                }
                break;
            case 1:
                if (CommonUtils.getInstance().getSite() == 140) {
                    instList.clear();
                    adapterList.clear();
                    for (int i = 0; i < mDataList.size(); i++) {
                        if (mDataList.get(i).getType().equals("NORMAL")) {
                            if (mDataList.get(i).getLevel() == 1) {
                                instList.add(mDataList.get(i));
                            }
                        }
                    }
                    adapterList.addAll(instList);
                    if (commonAdapter != null) {
                        commonAdapter.notifyDataSetChanged();
                    }
                } else {
                    for (int i = 0; i < mDataList.size(); i++) {
                        if (mDataList.get(i).getType().equals("NORMAL")) {
                            if (mDataList.get(i).getLevel() == 1) {
                                indexList.add(mDataList.get(i));
                            }
                        }
                    }
                }
                break;
            case 2:
                if (CommonUtils.getInstance().getSite() == 140) {
                    adapterList.clear();
                    siteList.clear();
                    for (int i = 0; i < mDataList.size(); i++) {
                        if (mDataList.get(i).getType().equals("NORMAL")) {
                            if (mDataList.get(i).getLevel() == 2) {
                                siteList.add(mDataList.get(i));
                            }
                        }
                    }

                    adapterList.addAll(siteList);
                    if (commonAdapter != null) {
                        commonAdapter.notifyDataSetChanged();
                    }
                } else {
                    for (int i = 0; i < mDataList.size(); i++) {
                        if (mDataList.get(i).getType().equals("NORMAL")) {
                            if (mDataList.get(i).getLevel() == 2) {
                                indexList.add(mDataList.get(i));
                            }
                        }
                    }
                }
                break;
            case 3:
                for (int i = 0; i < mDataList.size(); i++) {
                    if (mDataList.get(i).getType().equals("ENTERPRISE")) {
                        indexList.add(mDataList.get(i));
                    }
                }
                break;
            default:
                if (CommonUtils.getInstance().getSite() == 140) {
                    for (int i = 0; i < mDataList.size(); i++) {
                        if (mDataList.get(i).getType().equals("NORMAL") && mDataList.get(i).getLevel() == 2) {

                        } else {
                            indexList.add(mDataList.get(i));
                        }
                    }
                } else {
                    indexList.addAll(mDataList);
                }

                break;
        }

        aMap.clear(true);

        refreshMap(indexList,false);
    }

    private void refreshMap(List<PracticeListBean> beanList,boolean showWindow) {
        latLngList.clear();
        int iconRes;
        for (int i = 0; i < beanList.size(); i++) {
            if (StringUtils.isEmpty(beanList.get(i).getLatitude()) || StringUtils.isEmpty(beanList.get(i).getLongitude())) {
                continue;
            }

            if (beanList.get(i).getType().equals("NORMAL")) {
                if (CommonUtils.getInstance().getSite() == 140) {
                    switch (beanList.get(i).getLevel()) {
                        case 0:
                            iconRes = R.drawable.practice_map_center_qixia;
                            break;
                        case 1:
                            iconRes = R.drawable.practice_map_inst_qixia;
                            break;
                        case 2:
                            iconRes = R.drawable.practice_map_site_qixia;
                            break;
                        default:
                            iconRes = R.drawable.practice_map_inst_qixia;
                            break;
                    }
                } else {
                    switch (beanList.get(i).getLevel()) {
                        case 0:
                            iconRes = R.drawable.practice_map_center;
                            break;
                        case 1:
                            iconRes = R.drawable.practice_map_inst;
                            break;
                        case 2:
                            iconRes = R.drawable.practice_map_site;
                            break;
                        default:
                            iconRes = R.drawable.practice_map_inst;
                            break;
                    }
                }

            } else {
                iconRes = R.drawable.practice_map_service;
            }

            LatLng latLng = new LatLng(Double.parseDouble(beanList.get(i).getLatitude()), Double.parseDouble(beanList.get(i).getLongitude()));
            Marker marker = aMap.addMarker(new MarkerOptions().position(latLng).title(beanList.get(i).getName()).snippet(beanList.get(i).getAddress() + "," + beanList.get(i).getTelephoneNum()).infoWindowEnable(true).draggable(false).icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                    .decodeResource(getResources(), iconRes))));
            marker.setAnchor(0.5f, 0.5f);
            latLngList.add(latLng);

            // 设置所有maker显示在当前可视区域地图中
            LatLngBounds.Builder builder = new LatLngBounds.Builder();
            for (LatLng latLng1 : latLngList) {
                builder.include(latLng1);
            }
            LatLngBounds build = builder.build();
            if(showWindow){
                marker.showInfoWindow();
            }
            aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(build, 10));
        }
    }

    @Override
    public void setError(String msg) {
        showToast(msg);
    }

    @Override
    public void onMapLoaded() {
        // 设置所有maker显示在当前可视区域地图中
        LatLngBounds.Builder builder = new LatLngBounds.Builder();
        for (LatLng latLng : latLngList) {
            builder.include(latLng);
        }
        LatLngBounds build = builder.build();

        aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(build, 10));
//        aMap.moveCamera(CameraUpdateFactory.zoomBy(2));
        aMap.setOnMapLoadedListener(this);//设置地图显示监听器
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        return false;
    }


    @Override
    public void onInfoWindowClick(Marker marker) {
        marker.showInfoWindow();
    }

    public class IndexBean implements Serializable {
        private String name;
        private int res;

        IndexBean(String name, int res) {
            this.name = name;
            this.res = res;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getRes() {
            return res;
        }

        public void setRes(int res) {
            this.res = res;
        }
    }
}
